var express = require('express');
var router = express.Router();
const mongodb= require('../components/mongo');
const host = require('../components/host');

const multer = require('multer');
const storage = multer.memoryStorage();
const uploader = multer({storage:storage});
const fs = require('fs');

/* GET home page. */
router.get('/',async function(req, res, next) {
   res.render('post_articleSample',{title:"postArticleSample"});
});

router.post('/',uploader.array('medias',9),async function(req, res) {
   console.log(req.body);
   var m_aid = Date.now().toString();
   var m_uid = req.body.u_id;
   var m_type = req.body.type;
   var m_content = req.body.content;
   var m_time_stamp = req.body.time_stamp;
   
   const local = "public/";
   const articles_storage_path = "storage/articles/";
   const dirPath = local + articles_storage_path + m_aid;
	   
   var exits = fs.existsSync(dirPath);   
   
   if(!exits){
		fs.mkdirSync(dirPath);    
	}
	
	console.log(req.files);
   
   var m_medias = [];
   for(var i = 0 ; i < req.files.length ; i++){
	   var fileFormat = (req.files[i].originalname).split(".");
	   var filename = req.files[i].fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1];
	   var filePath = dirPath + '/' + filename;
	   m_medias.push(host.HOST + articles_storage_path + m_aid + '/' + filename);
	   fs.writeFile(filePath,req.files[i].buffer,function(cb){});
   }
   
   var newArticleObj = {
	   u_id: m_uid,
	   a_id : m_aid,
	   type : m_type,
	   content : m_content,
	   medias: m_medias,
	   time_stamp : m_time_stamp,
	   supports :[],
	   comments :[],
   }
   const result = await mongodb.insert("Article",newArticleObj);
   res.json(newArticleObj);
});



module.exports = router;